package br.com.divulgaqui.persistence.daoimpl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.Query;

import br.com.divulgaqui.entity.Marca;
import br.com.divulgaqui.persistence.dao.JPAGenericDAO;
import br.com.divulgaqui.persistence.dao.MarcaDAO;

public class MarcaDAOImpl extends JPAGenericDAO<Marca> implements MarcaDAO{

	public MarcaDAOImpl(EntityManager entityManager) {
		super(entityManager);		
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Marca> listarMarcas() {
		StringBuilder sql = new StringBuilder("from Marca m \n");		
		sql.append("order by m.nome");
		Query query = this.getEntityManager().createQuery(sql.toString());
		return query.getResultList();		
	}

	@Override
	public Marca pesquisarMarcaPorNome(Long id, String nome) {
		StringBuilder sql = new StringBuilder("from Marca m \n");		
		sql.append("where UPPER(m.nome) = \n");
		sql.append("'"+nome.toUpperCase()+"' \n");
		sql.append("and m.id != "+id+"");
		Query query = this.getEntityManager().createQuery(sql.toString());
		Marca marca = null;
		try {
			marca = (Marca) query.getSingleResult();
		} catch (NoResultException e) {
			return null;
		}
		return marca;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Marca> listarMarcasAtiva() {
		StringBuilder sql = new StringBuilder("from Marca m \n");	
		sql.append("where m.ativo = true \n");
		sql.append("order by m.nome");
		Query query = this.getEntityManager().createQuery(sql.toString());
		return query.getResultList();	
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Marca> qtdProdutosPorMarca() {
		StringBuilder sql = new StringBuilder("from Marca m \n");	
		sql.append("left outer join fetch m.modelos \n");
		sql.append("order by m.nome");
		Query query = this.getEntityManager().createQuery(sql.toString());
		return query.getResultList();
	}
}
